// pages/subscribe-message/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    switchChecked: false,
    isShowSetModel: false,
    showModelContent: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  // 消息订阅
  subscribeMessage(){
    // 请求发送订阅消息权限
    wx.requestSubscribeMessage({
      tmplIds: ['XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8'],
      success: (res) => { 
        console.log(res);
      },
      fail: (err) => {
        console.log(err);
      },
      complete: com => {
        console.log(com);
      }
    })
  },


    /**
   * 消费者确认预约
   */
  consumersConfirmReservation(e){
    const {studioId, itemName, numberOfPeople, selectedDate} = e.detail.value
    console.log(e);
    wx.showLoading({
      title: '正在处理',
      mask: true
    })
    const checkedTime = this.timeCheckedArr()
    if (itemName === '') {
      wx.hideLoading()
      wx.showModal({
        title: '友情提示',
        content: '您暂未选择预约项目',
        showCancel: false,
        confirmColor: '#C5AF6F'
      })
      return false
    }
    if (checkedTime.length === 0) {
      wx.hideLoading()
      wx.showModal({
        title: '友情提示',
        content: '您暂未选择预约区间',
        showCancel: false,
        confirmColor: '#C5AF6F'
      })
      return false
    }
    if (checkedTime.length === 1) {
      wx.hideLoading()
      wx.showModal({
        title: '友情提示',
        content: '还需选择一个预约时间组成区间',
        showCancel: false,
        confirmColor: '#C5AF6F'
      })
      return false
    }
    const startTime = moment((selectedDate + ' ' + checkedTime[0].time + ':00'), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
    const endTime = moment((selectedDate + ' ' + checkedTime[1].time + ':00'), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
    
    const sendData = {
      template_id: 'XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8', //所需下发的订阅模板id
      page: '/store-studio/pages/reservation-consumers-list/index', //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转
      data: { //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }的object
        "thing1": { //服务门店
          "value": wx.getStorageSync('studioName')
        },
        "name2": { // 服务项目
          "value": itemName
        },
        "thing3": { //服务描述
          "value": ''
        },
        "date4": { //服务日期
          "value": moment().format('YYYY-MM-DD HH:mm:ss')
        },
        "phrase6": { //订单状态
          "value": '发起预约'
        },
      },
      miniprogram_state: 'formal', //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
      lang: 'zh_CN', // 进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为
    }

    const formData = {
      studioId: parseInt(studioId), //工作室id
      itemName, //预约项目名称
      numberOfPeople: parseInt(numberOfPeople), //人数
      startTime, //预约开始时间
      endTime, //预约结束时间
    }
    console.log(formData);
    // if (this.data.switchChecked) {
      this.consumerSubscribeMessage(formData)
    // }else{
    //   this.reservationConsumersAdd(formData)
    // }
  },

    /**
   * 消费者订阅相关信息
   */
  consumerSubscribeMessage(formData){
    const that = this
    // 请求发送订阅消息权限
    if (wx.requestSubscribeMessage){
      wx.requestSubscribeMessage({
        tmplIds: ['XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8'],
        success: (res) => { 
          console.log(res);
          if (res.XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8 == 'accept') {
            that.reservationConsumersAdd(formData)
          }
          if (res.XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8 == 'reject') {
            that.reservationConsumersAdd(formData)
            // wx.hideLoading()
            // wx.showToast({
            //   title: '您拒绝了订阅通知,将不会收到服务通知',
            //   icon: 'none',
            //   mask: true
            // })
            // setTimeout(() => {
            //   wx.showLoading({
            //     title: '正在处理',
            //     mask: true
            //   })
            //   that.reservationConsumersAdd(formData)
            // }, 3000)
          }
        },
        fail: (err) => {
          wx.hideLoading()
          console.log(err);
          // 20004:用户关闭了主开关，无法进行订阅,引导开启
          if (err.errCode == 20004) {
          // 显示引导设置弹窗
          that.setData({
            isShowSetModel: true,
            showModelContent: '检测到您未开启订阅消息通知权限，是否去设置？'
          })
        }else{
          // 其他错误信息码，对应文档找出原因
          wx.showModal({
            title: '提示',
            content: err.errMsg,
            showCancel: false
          })
        }
        },
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '请更新您微信版本，来获取订阅消息功能',
        showCancel: false
      })
    }
  },

    /**
   * 发起预约提交
   * @param {*} formData 发送的数据
   */
  reservationConsumersAdd(formData){
    reservationConsumersAddApi(wx.getStorageSync('token'), formData).then(addRes => {
      if (addRes.data.code === 200) {
        wx.hideLoading()
        wx.showToast({
          title: '预约成功',
          mask: true,
          success: () => {
            this._sendNotification({id: addRes.data.data})
            setTimeout(() => {
              wx.navigateBack()
            }, 2000)
          }
        })
      }else if (addRes.data.code === 500) {
        wx.hideLoading()
        console.log('预约项目列表  500');
      }else if (addRes.data.code === 401) {
        wx.hideLoading()
        app.login(wx.getStorageSync('phone'))
      }
    }).catch(addErr => {
      wx.hideLoading()
      console.log(addErr);
    })
  },

      /**
   * 发送通知
   * @param {*} item
   */
  _sendNotification(item){
    console.log('发送通知');
    
    // new 一个FormData对象
    let formData = new FormData()
    formData.append('id', item.id)
    formData.append('notified', 1)
    let data = formData.getData()
    const header = {
      'content-type': data.contentType,
    }
    sendNotificationApi(wx.getStorageSync('token'), header, data.buffer).then((res) => {
      console.log(res);
      if (res.data.code === 200) {
        console.log('发送通知 200');
      }else if (res.data.code === 500){
        console.log('发送通知 500');
      }else if (res.data.code === 401){
        app.login(wx.getStorageSync('phone'))
        this._sendNotification(item)
      }
    })
  },


  
  /**
   * 商家订阅相关信息
   */
  consumerSubscribeMessage(operation, formData){
    const that = this
    // 请求发送订阅消息权限
    if (wx.requestSubscribeMessage) {
      wx.requestSubscribeMessage({
        tmplIds: ['XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8'],
        success: (res) => { 
          console.log(res);
          if (res.XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8 == 'accept') {
            if (operation === 'cancle') {
              that._cancleReservation(formData)
            }else if (operation === 'confirm') {
              that._confirmReservation(formData)
            }
          }else if (res.XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8 == 'reject') {
            wx.showToast({
              title: '您拒绝了订阅通知,将不会收到服务通知',
              icon: 'none',
              mask: true
            })
            if (operation === 'cancle') {
              that._cancleReservation(formData)
            }else if (operation === 'confirm') {
              that._confirmReservation(formData)
            }
          }else{
            wx.showToast({
              title: '授权订阅消息有误',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.log(err);
           // 20004:用户关闭了主开关，无法进行订阅,引导开启
           if (err.errCode == 20004) {
          	// 显示引导设置弹窗
            that.setData({
              isShowSetModel: true,
              showModelContent: '检测到您未开启订阅消息通知权限，是否去设置？'
            })
          }else{
          	// 其他错误信息码，对应文档找出原因
            wx.showModal({
              title: '提示',
              content: err.errMsg,
              showCancel: false
            })
          }
        },
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '请更新您微信版本，来获取订阅消息功能',
        showCancel: false
      })
    }
  },

  /**
   * 取消预约
   * @param {*} item
   */
  _cancleReservation(item){
    console.log('商家取消预约');
    const sendData = {
      template_id: 'XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8', //所需下发的订阅模板id
      page: '/store-studio/pages/reservation-merchants-list/index', //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转
      data: { //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }的object
        "thing1": { //服务门店
          "value": wx.getStorageSync('studioName')
        },
        "name2": { // 服务项目
          "value": item.itemName
        },
        "thing3": { //服务描述
          "value": ''
        },
        "date4": { //服务日期
          "value": moment().format('YYYY-MM-DD HH:mm:ss')
        },
        "phrase6": { //订单状态
          "value": '预约成功'
        },
      },
      miniprogram_state: 'formal', //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
      lang: 'zh_CN', // 进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为
    }

    // new 一个FormData对象
    let formData = new FormData()
    formData.append('id', item.id)
    let data = formData.getData()
    const header = {
      'content-type': data.contentType,
    }
    reservationMerchantsCancelApi(wx.getStorageSync('token'), header, data.buffer).then((res) => {
      console.log(res);
      if (res.data.code === 200) {
        wx.showToast({
          title: '取消预约成功',
          icon: 'none',
          mask: true,
          success: () => {
            this.setData({
              reservationList: [],
              pageNum: 0,
              nomore: false
            })
            this.getReservationList(this.data.tabs[this.data.activeIndex].type, this.data.startTime, this.data.endTime)
            this._sendNotification(item) //发送通知
          }
        })
      }else if (res.data.code === 500){
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          mask: true,
        })
      }
    })
  },

  /**
   * 确认预约
   * @param {*} item
   */
  _confirmReservation(item){
    console.log('确认预约');
    const sendData = {
      template_id: 'XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8', //所需下发的订阅模板id
      page: '/store-studio/pages/reservation-merchants-list/index', //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转
      data: { //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }的object
        "thing1": { //服务门店
          "value": wx.getStorageSync('studioName')
        },
        "name2": { // 服务项目
          "value": item.itemName
        },
        "thing3": { //服务描述
          "value": ''
        },
        "date4": { //服务日期
          "value": moment().format('YYYY-MM-DD HH:mm:ss')
        },
        "phrase6": { //订单状态
          "value": '预约成功'
        },
      },
      miniprogram_state: 'formal', //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
      lang: 'zh_CN', // 进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为
    }

    // new 一个FormData对象
    let formData = new FormData()
    formData.append('id', item.id)
    let data = formData.getData()
    const header = {
      'content-type': data.contentType,
    }
    reservationMerchantsConfirmApi(wx.getStorageSync('token'), header, data.buffer).then((res) => {
      console.log(res);
      if (res.data.code === 200) {
        wx.showToast({
          title: '确认预约成功',
          icon: 'none',
          mask: true,
          success: () => {
            this.setData({
              reservationList: [],
              pageNum: 0,
              nomore: false
            })
            this.getReservationList(this.data.tabs[this.data.activeIndex].type, this.data.startTime, this.data.endTime)
            this._sendNotification(item)
          }
        })
      }else if (res.data.code === 500){
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          mask: true,
        })
      }
    })
  },

  /**
   * 发送通知
   * @param {*} item
   */
  _sendNotification(item){
    console.log('发送通知');
    
    // new 一个FormData对象
    let formData = new FormData()
    formData.append('id', item.id)
    formData.append('notified', 0)
    let data = formData.getData()
    const header = {
      'content-type': data.contentType,
    }
    sendNotificationApi(wx.getStorageSync('token'), header, data.buffer).then((res) => {
      console.log(res);
      if (res.data.code === 200) {
        console.log('发送通知 200');
      }else if (res.data.code === 500){
        console.log('发送通知 500');
      }else if (res.data.code === 401){
        app.login(wx.getStorageSync('phone'))
        this._sendNotification(item)
      }
    })
  },


  /**
   * 开始预约通知
   * @param {*} e 
   */
  onChange({ detail }) {
    if (this.data.switchChecked) {
      this.setData({
        isShowSetModel: true,
        showModelContent: '设置订阅消息通知权限关闭，是否去设置？'
      })
      // this.setData({ switchChecked: false });
      return
    }
    // 请求发送订阅消息权限
    if (wx.requestSubscribeMessage) {
      wx.requestSubscribeMessage({
        tmplIds: ['XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8'],
        success: (res) => { 
          console.log(res);
          if (res.XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8 == 'accept') {
            // 需要手动对 checked 状态进行更新
            this.setData({ switchChecked: true });
          }else if (res.XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8 == 'reject') {
            // 显示引导设置弹窗
            this.setData({
              isShowSetModel: true,
              showModelContent: '您拒绝了订阅通知，后续无法使用该功能，是否去设置？'
            })

            // 需要手动对 checked 状态进行更新
            // this.setData({ switchChecked: false });
          }else{
            wx.showToast({
              title: '授权订阅消息有误',
              icon: 'none'
            })
          }
          // wx.setStorageSync('switchChecked', this.data.switchChecked)
        },
        fail: (err) => {
          console.log(err);
           // 20004:用户关闭了主开关，无法进行订阅,引导开启
           if (err.errCode == 20004) {
          	// 显示引导设置弹窗
            this.setData({
              isShowSetModel: true,
              showModelContent: '检测到您未开启订阅消息通知权限，是否去设置？'
            })
          }else{
          	// 其他错误信息码，对应文档找出原因
            wx.showModal({
              title: '提示',
              content: err.errMsg,
              showCancel: false
            })
          }
        },
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '请更新您微信版本，来获取订阅消息功能',
        showCancel: false
      })
    }
  },

  closeSetModel(){
    this.setData({
      isShowSetModel: false,
    })
  },

  openSetCallback(e){
    console.log(e);
    wx.openSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log(res);
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },

  getSetting(){
    this.setData({
      isShowSetModel: false,
    })
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log(res.authSetting)
        console.log(res.subscriptionsSetting)
       const switchChecked = (res.subscriptionsSetting.mainSwitch && res.subscriptionsSetting.itemSettings && res.subscriptionsSetting.itemSettings.XRdgBppoGK6Y8Dp7O4wnB_6yyiErOfqobkFgv0_AO_8 === 'accept') ? true : false
      //  const switchChecked = res.subscriptionsSetting.mainSwitch ? true : false  //订阅总开关是否打开
        this.setData({
          switchChecked,
          isShowSetModel: false,
        })
      },
      fail (err) {
        console.log(err);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})